import {
  wxRequest
} from '../../../utils/server.js';
const _wxRequest = new wxRequest();
let util = require('../../../utils/util.js');
const app = getApp()
Page({
  data: {
    imgUrl: app.globalData.imgUrl,
    contentImgsnum: 1,
    canUseLocation: false,
    id: '',
    isHide: false,
    cententDetail: {
      correct: false,
      formulaCustomized: false,
      dyeNum: ''
    },
    uploadUrl: wx.getStorageSync('uploadUrl'),
    hideSup: true,
    loading: false,
    isIphoneX: app.globalData.isIphoneX,
    coverImgs: [],
    supId: '',
    extraNodes: [
      {
        type: "after",
        dragId: "plus",
        slot: "plus",
        fixed: true
      }
    ],
    pageMetaScrollTop: 0,
    scrollTop: 0,
    contentImgs: [],//介绍图

    dyeColorSetJson: [],

    uiList: [
      {
        name: "/pages/dye_paste/index",
        url: "/pages/dye_paste/index"
      },
    ],
    UiIndex:0
  },


  onLoad: function (options) {
    if (options?.supId) {
      this.setData({
        supId: options.supId
      })
    }
    if (options && options.id) {
      this.setData({
        id: options.id
      })

      // this.getdetail()
      // this.getImg() 
    }
    this.getSupplierList()
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on && eventChannel.on('deviceItem', (data = {}) => {
      // 这里未触发
      console.log(data)
      const UiIndex = this.data.uiList.findIndex(e=>e.url == data.url)
      this.setData({
        cententDetail: data,
        UiIndex,
        contentImgs: [{
          imgName: '',
          imgPath: data.coverImg,
          fixed: false
        }]
      })
      // 如何是定制配置
      if (data.formulaCustomized == 1) {
        //传入选中定制配置方法
        this.changeFormulaCustomized({ detail: { value: true }, target: { dataset: { dyeColorSetJson: data.dyeColorSetJson } } })
      }
    })
    //介绍图
    this.dragcontentImgs = this.selectComponent('#dragcontentImgs');
    this.dragcontentImgs.init();

  },

  onShow: function () {
  },

  handleChoose: function (e) {
    var params = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/publish/template/commonlist?apiurl=' + params.apiurl + '&name=' + params.name + '&itemName=' + params.itemname + '&addUrl=' + params.addurl
    })
  },

  // 获取列表
  getSupplierList: function () {
    var that = this
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/org/protected/bizOrg/findSupplierList',
      method: 'POST',
      data: {}
    }, (res) => {
      var list = res.list
      if (list.length > 0) {
        if (this.data.supId) {
          let supplyItem = list.filter(item => item.id == this.data.supId)[0];
          console.log(supplyItem);
          this.setData({
            supplyItem
          })
        } else {
          that.setData({
            supplyItem: {
              id: list[0].id,
              supName: list[0].supName
            }
          })
        }


      }
    })
  },
  //选择商品图片
  chooseGoodsImg: function (e) {
    this.setData({
      imgs: this.coverImgs.data.imgs,
      isHide: true
    })
  },

  deleteGoodsImg: function (e) {
    this.setData({
      imgs: this.coverImgs.data.imgs
    })
  },

  deloriginGoodsImg: function () {
    this.setData({
      originImgs: this.details.data.originImgs
    })
  },

  completefun: function () {
    console.log('wanc')
    this.setData({
      isHide: false
    })
  },

  //选择介绍图片
  choosecontentImgs: function (e) {
    this.setData({
      imgs: this.coverImgs.data.imgs
    })
  },

  deletecontentImgs: function (e) {
    this.setData({
      imgs: this.coverImgs.data.imgs
    })
  },

  delorigincontentImgs: function () {
    this.setData({
      originImgs: this.details.data.originImgs
    })
  },

  setDyeNumValue(e) { //获取输入的染膏数
    this.setData({ cententDetail: { ...this.data.cententDetail, ...{ dyeNum: e.detail.value } } })
  },

  changeFormulaCustomized(e) {
    console.log('选中是否定制', e)
    const dyeColorSetJsonText = e.target.dataset.dyeColorSetJson
    const ischecked = e.detail.value
    let cententDetail = this.data.cententDetail
    if (!this.data.cententDetail.dyeNum) {
      wx.showToast({
        icon: 'none',
        title: '请先输入染膏数量',
      })
      cententDetail.formulaCustomized = false
      this.setData({ cententDetail })
      return
    }
    if (ischecked) {
      _wxRequest.wxTonkenAjax({
        url: app.globalData.apiUrl + "/gds/protected/deviceType/getDyeList?dtoName=DyeColorSetDTO&dyeNum=" + this.data.cententDetail.dyeNum,
        method: 'GET',
      }, (res) => {
        let dyeColorSetJson = res.list
        if (dyeColorSetJsonText && dyeColorSetJsonText != undefined) { //如是编辑的情况
          const dyeColorSetArray = JSON.parse(dyeColorSetJsonText) //选中的染膏头
          dyeColorSetJson = dyeColorSetJson.map(d => { const o2 = dyeColorSetArray.find(e => e.cnum == d.cnum); return o2 || d })
        }
        this.setData({ dyeColorSetJson })
      })
    }
    cententDetail.formulaCustomized = ischecked
    this.setData({ cententDetail })
  },

  checkboxChange(e) { // 选择双氧头
    console.log(e.detail.value)
    let list = e.detail.value
    if (list.length > 2) {
      wx.showToast({
        icon: 'none',
        title: '不能超过两个双氧头',
      })
      return
    }
    const devList = this.data.dyeColorSetJson
    const dyeColorSetJson = devList.map(d => { list.includes(d.cnum) ? d.o2 = 1 : d.o2 = 0; return d })
    console.log(dyeColorSetJson)
    this.setData({ dyeColorSetJson })
  },
  seto2Pc(e) {
    console.log(e)
    const o2Pc = e.detail.value
    const cnum = e.currentTarget.dataset.cnum
    const devList = this.data.dyeColorSetJson
    const dyeColorSetJson = devList.map(d => { d.cnum == cnum && (d.o2Pc = o2Pc); return d })
    this.setData({ dyeColorSetJson })
    console.log(dyeColorSetJson)
  },

  goback: function () {
    wx.navigateBack({

    })
  },


  //表单提交
  formSubmit: function (e) {
    var formdata = e.detail.value;
    formdata.supId = this.data.supplyItem.id;
    formdata.supName = this.data.supplyItem.supName;
    if (formdata.typeName == '') {
      wx.showToast({
        icon: 'none',
        title: '设备名称不能为空',
      })
      return
    }

    if (formdata.code == '') {
      wx.showToast({
        icon: 'none',
        title: '广告类型ID不能为空',
      })
      return
    }

    if (formdata.dyeNum == '') {
      wx.showToast({
        icon: 'none',
        title: '染膏数量不能为空',
      })
      return
    }

    if (formdata.formulaGroupCode == '') {
      wx.showToast({
        icon: 'none',
        title: '配方字典组不能为空',
      })
      return
    }


    if (this.data.contentImgs.length < 1) {
      wx.showToast({
        icon: 'none',
        title: '请上传图片',
      })
      return
    }


    formdata.coverImg = this.data.contentImgs[0].imgPath

    formdata.correct = formdata.correct ? 1 : 0 //电子秤校准
    formdata.formulaCustomized = formdata.formulaCustomized ? 1 : 0//定制配方
    //筛选双氧头
    const dyeColorSetJson = this.data.dyeColorSetJson.filter(d => d.o2 == 1)
    formdata.dyeColorSetJson = JSON.stringify(dyeColorSetJson)

    console.log(formdata, 'formdata')
    this.formRequest(formdata);
  },




  //请求
  formRequest: function (formdata) {
    var url = '/gds/protected/comm/beanCrud/iot.DeviceTypeVO/create';
    var title = "发布成功"
    //修改
    if (this.data.id) {
      url = "/gds/protected/comm/beanCrud/iot.DeviceTypeVO/update";
      formdata.id = this.data.cententDetail.id;
      title = "修改成功"
    }

    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url,
      method: 'POST',
      data: formdata
    }, (res) => {
      console.log(res)
      wx.showToast({
        title,
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/publish/device/type',
        })
      }, 1500)

    })
  },

  //获取设备详情
  getdetail: function () {
    var that = this
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/comm/beanCrud/iot.DeviceTypeVO/getById/' + this.data.id,
      method: 'get'
    }, (res) => {

      if (res && res.vo) {
        var data = res.vo
        that.setData({
          cententDetail: data,
          supplyItem: {
            supName: data.supName,
            id: data.supId
          },
        })
        // that.dragcoverImgs.init()
        // that.dragcontentImgs.init() 

      }


    })
  },








  // 获取轮播图和介绍图片
  getImg: function () {
    var that = this
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/device/queryTypeList',
      method: 'post',
      data: {
        id: this.data.id,
        pageSize: 100
      }
    }, (res) => {
      var coverImgs = [],
        contentImgs = []
      var list = res.list;
      list.map((item) => {
        if (item.imgType == 1) {
          coverImgs.push(item)
        } else if (item.imgType == 2) {
          contentImgs.push(item)
        }
      })




      //拖拽coverImgs 
      if (contentImgs.length > 0) {
        contentImgs.map(item => {
          item.fixed = false
        })
      }

      that.dragcontentImgs.init()
    })
  },






  // *********介绍图录播 *********
  contentSortEnd(e) {
    this.setData({
      contentImgs: e.detail.listData
    });
  },
  contentChange(e) {
    this.setData({
      contentImgs: e.detail.listData
    });
    this.dragcontentImgs.init()
  },
  contentSizeChange(e) {
    wx.pageScrollTo({ scrollTop: 0 })
    this.setData({
      size: e.detail.value
    });
    this.dragcontentImgs.init();
  },

  contentItemClick(e) {
    console.log(e);
  },
  contentToggleFixed(e) {
    let key = e.currentTarget.dataset.key;
    let { contentImgs } = this.data;
    contentImgs[key].fixed = !contentImgs[key].fixed
    this.setData({
      contentImgs: contentImgs
    });
    this.dragcontentImgs.init();
  },

  contentAdd(e) {
    let contentImgs = this.data.contentImgs;
    var that = this
    wx.chooseImage({
      count: that.data.contentImgsnum - that.data.coverImgs.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        that.uploadFile(res.tempFilePaths, 'contentImgs')
      }
    });
  },










  //上传图片
  uploadFile: function (pics, idName) {
    var that = this;
    var listData = this.data[idName]
    this.setData({
      loading: true
    })
    for (var i = 0; i < pics.length; i++) {
      (function (i) {
        //   setTimeout(function () { 
        wx.uploadFile({
          url: app.globalData.apiUrl + '/gds/protected/comm/file/iot.DeviceTypeVO/fileUpload',
          header: {
            "Authorization": wx.getStorageSync('Authorization'),
          },
          formData: {
            width: 750
          },
          filePath: pics[i],
          name: 'file',
          success: function (res) {
            if (typeof res.data == "string") {
              var resdata = JSON.parse(res.data)
            }
            if (resdata.success) {

              var item = {
                imgName: resdata.datas.vo.fileName,
                imgPath: resdata.datas.vo.relativeFilePath,
                fixed: false
              }
              listData.push(item)
              that.setData({
                [idName]: listData
              })

              //初始化组件
              if (idName == 'coverImgs') {
                that.dragcoverImgs.init();
              } else if (idName == 'contentImgs') {
                that.dragcontentImgs.init();
              }

              //最后一张关闭遮罩 
              console.log(i + 1 == pics.length, 'last')
              if (i + 1 == pics.length) {
                that.setData({
                  loading: false
                })
              }

            }
          },
          fail: function (res) {
            // wx.showToast({
            //   icon: 'none',
            //   title: '图片上传失败',
            // })
          }
        })
        //   }, (i + 1) * 800);
      })(i)
    }
  },

  scroll(e) {
    this.setData({
      pageMetaScrollTop: e.detail.scrollTop
    })
  },

  // 页面滚动
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    });
  },

  UiChange(e){
    const index = e.detail.value
    this.setData({UiIndex:index})
  }
})